package com.bort.system.utils;

import com.fazecast.jSerialComm.SerialPort;
import org.springframework.stereotype.Component;

@Component
public class LightControlUtils {

    SerialPort getPort(){
        SerialPort[] ports = SerialPort.getCommPorts();
        if(ports.length >= 1){
           return ports[0];
        }
        return null;
    }

    public void portWrite(SerialPort comPort,String msg){
        comPort.setComPortParameters(9600, 8, 1, 0); // 设置波特率、数据位、停止位和校验方式
        comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
        try {
            if (comPort.openPort()) {
                System.out.println("串口打开成功");
                comPort.writeBytes(msg.getBytes(), 5000); // 写入数据到串口，超时时间5000ms
                byte[] buffer = new byte[100];
                int bytesRead = comPort.readBytes(buffer, buffer.length); // 从串口读取数据
                System.out.println("接收到的数据: " + new String(buffer, 0, bytesRead));
                comPort.closePort();  // 关闭串口
            } else {
                System.out.println("无法打开串口");
            }
        } catch (Exception e) {
            System.out.println("发生异常: " + e.getMessage());
        }
    }
}
